package com.traffic.api.listener;

import com.traffic.api.cache.MapCacheUtils;
import com.traffic.api.entity.VirtualTransitCard;
import com.traffic.api.service.VirtualTransitCardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import java.util.HashMap;
import java.util.List;


/**
 * churcy
 */
public class SpringApplicationListener extends ContextLoaderListener {

    private MapCacheUtils mapCacheUtils = MapCacheUtils.getInstance();

    private final static Logger LOG = LoggerFactory.getLogger(SpringApplicationListener.class);

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        super.contextDestroyed(event);
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        super.contextInitialized(event);
        LOG.info("加载一系列初始化……");
        ServletContext servletContext = event.getServletContext();

        ApplicationContext context = (WebApplicationContext) servletContext
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

        VirtualTransitCardService cardService = (VirtualTransitCardService) context.getBean("virtualTransitCardServiceImpl");
        //加载会员卡缓存
        List<VirtualTransitCard> virtualTransitCards = cardService.findByConditions(new HashMap<>());

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (VirtualTransitCard virtualTransitCard : virtualTransitCards) {
                    mapCacheUtils.getCardMap().put("CARD_NO:" + virtualTransitCard.getCardNo(), virtualTransitCard.getCardNo());
                }

                LOG.info("初始化操作操作成功，初始化卡数量为：" + virtualTransitCards.size());
            }
        }).start();

    }

}
